/**
 * Title:UserRoleService<br>
 * Description:用户角色服务类<br>
 * Copyright © Xiamen Dripstill  NetWorks Co.,Ltd.
 * @Create:2018-07-03<br>
 * @author:Sun Yijing<br>
 * @version: Object v1.0.0<br>
 * <br>
 * 修改历史:<br>
 * 修改人		修改日期		修改描述<br>
 * -----------------------------------<br>
 * <br>
 * <br>
 */
package com.yoooya.base.service;

import com.yoooya.base.commons.CommonUtils;
import com.yoooya.base.dao.system.DepartmentMapper;
import com.yoooya.base.dao.system.UserDepartmentMapper;
import com.yoooya.base.dao.system.UserInfoMapper;
import com.yoooya.base.model.po.system.DepartmentPo;
import com.yoooya.base.model.po.system.UserDepartmentPo;
import com.yoooya.base.model.po.system.UserInfoPo;
import com.yoooya.base.service.system.DepartmentService;
import com.yoooya.base.third.model.vo.cp.WxCpDepart;
import com.yoooya.base.third.model.vo.cp.WxCpUser;
import com.yoooya.base.third.service.WxCpService;
import com.yoooya.base.utils.IdUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class WechatSyncService {

	@Autowired
	private DepartmentMapper departmentMapper;
	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private UserInfoMapper userInfoMapper;
	@Autowired
	private WxCpService wxCpService;
	@Autowired
	private UserDepartmentMapper userDepartmentMapper;
//	@Autowired
//	private CallSeatMapper callSeatMapper;

	private static final Logger logger = LoggerFactory.getLogger(WechatSyncService.class);

	/**
	 * 同步企业微信用户数据
	 */
	public void syncByUser() {
		try {
			List<WxCpUser> cpUsers = wxCpService.userList(1, true, 0);
			List<UserInfoPo> users = new ArrayList<UserInfoPo>();
			UserInfoPo user = null;
			UserInfoPo temp = null;
			List<UserDepartmentPo> departs = new ArrayList<UserDepartmentPo>();
			for (WxCpUser cpUser : cpUsers) {
				user = this.userInfoMapper.queryByUserId(cpUser.getUserId());
				if (user != null) {
					temp = new UserInfoPo();
					temp.setId(user.getId());

					temp.setNickname(cpUser.getName());
					temp.setUserName(cpUser.getUserId().toLowerCase());
					temp.setName(cpUser.getName());
					temp.setMobile(cpUser.getMobile());
					temp.setPost(cpUser.getPosition());
					temp.setGender(cpUser.getGender());
					temp.setEmail(cpUser.getEmail());
					//cjianquan 2019/9/23 该字段以内部设置为准
//					temp.setIsLeader(cpUser.getIsleader());
					temp.setTelephone(cpUser.getTel());
					temp.setEnable(cpUser.getEnable());
					if (cpUser.getEnable() == null) {
						temp.setEnable(1);
					}
					temp.setEnglishName(cpUser.getEnglishName());
					temp.setCpStatus(cpUser.getStatus());
					temp.setQrCode(cpUser.getQrCode());
					temp.setPortrait(cpUser.getAvatar());
					String ids = CommonUtils.listToString(cpUser.getDepartIds(), ",");
					Date now = new Date();
					if (StringUtils.isNoneBlank(ids)) {
						userDepartmentMapper.deleteByUser(user.getId());
						temp.setDepartmentIds(ids);
						temp.setDepartment(this.departmentService.queryNameByIds(ids));
						UserDepartmentPo depart = null;
						for (int i = 0; i < cpUser.getDepartIds().length; i++) {
							depart = new UserDepartmentPo();
							depart.setUserId(user.getId());
							depart.setDepartmentId(cpUser.getDepartIds()[i].longValue());
							depart.setId(IdUtils.id());
							depart.setCreateTime(now);
							departs.add(depart);
						}
					}
					temp.setModifyTime(now);
					temp.setStatus(1);
					temp.setSyncStauts(2);
					temp.setSyncTime(now);
					temp.setSyncType(2);

					userInfoMapper.updateById(temp);
				} else {
					user = new UserInfoPo();
					Date now = new Date();
					user.setId(IdUtils.id());
					user.setCreateTime(now);
					user.setModifyTime(now);

					user.setName(cpUser.getName());
					user.setNickname(cpUser.getName());
					user.setUserName(cpUser.getUserId().toLowerCase());
					user.setUserId(cpUser.getUserId());
					String ids = CommonUtils.listToString(cpUser.getDepartIds(), ",");
					if (StringUtils.isNoneBlank(ids)) {
						user.setDepartmentIds(ids);
						user.setDepartment(this.departmentService.queryNameByIds(ids));
						UserDepartmentPo depart = null;
						for (int i = 0; i < cpUser.getDepartIds().length; i++) {
							depart = new UserDepartmentPo();
							depart.setUserId(user.getId());
							depart.setDepartmentId(cpUser.getDepartIds()[i].longValue());
							depart.setId(IdUtils.id());
							depart.setCreateTime(now);
							departs.add(depart);
							if (i == 0) {
								DepartmentPo department = this.departmentService
										.queryById(cpUser.getDepartIds()[i].longValue());
								/*if (department != null && department.getServiceType() != null
										&& department.getServiceType() == 1) {
									user.setRole("销售顾问");
									user.setRoleIds("1610838954737752");
									user.setPosition("销售顾问");
									user.setPositionId(1610928587014419l);
								}*/
							}
						}
					}

					user.setMobile(cpUser.getMobile());
					user.setPost(cpUser.getPosition());
					user.setGender(cpUser.getGender());
					user.setEmail(cpUser.getEmail());
					user.setIsLeader(cpUser.getIsleader());
					user.setTelephone(cpUser.getTel());
					user.setEnable(cpUser.getEnable());
					if (cpUser.getEnable() == null) {
						user.setEnable(1);
					}
					user.setEnglishName(cpUser.getEnglishName());
					user.setCpStatus(cpUser.getStatus());
					user.setQrCode(cpUser.getQrCode());
					user.setPortrait(cpUser.getAvatar());

					user.setStatus(1);
					user.setIsLock(false);
					user.setAddType(1);
					user.setSyncStauts(2);
					user.setSyncTime(now);
					user.setSyncType(2);
					user.setPassword(CommonUtils.md5(CommonUtils.INIT_PASSWORD));
					users.add(user);
				}
			}
			if (CollectionUtils.isNotEmpty(departs)) {
				this.userDepartmentMapper.insertByBatch(departs);
			}
			if (CollectionUtils.isNotEmpty(users)) {
				this.userInfoMapper.insertByBatch(users);
			}

		} catch (Exception e) {
			logger.warn("syncByUser Exception: ", e);
		}

	}

	public void addDepart() {
		/*try {
			List<DepartmentPo> pos = departmentMapper.querByOld();
			WxCpDepart depart = null;
			for (DepartmentPo po : pos) {
				depart = new WxCpDepart();
				depart.setId(po.getId().intValue());
				depart.setName(po.getName());
				depart.setOrder(po.getId().intValue());
				depart.setParentId(po.getParentId().intValue());
				wxCpService.departCreate(depart);
			}
		} catch (Exception e) {
			logger.warn("syncByDepart Exception: ", e);
		}*/
	}

	/**
	 * 同步企业微信部门数据
	 */
	public void syncByDepart() {
		try {
			List<WxCpDepart> departs = wxCpService.departGet(null);
			List<DepartmentPo> pos = new ArrayList<DepartmentPo>();
			DepartmentPo po = null;
			DepartmentPo temp = null;
			for (WxCpDepart depart : departs) {
				po = this.departmentMapper.queryById((long) depart.getId());
				Date now = new Date();
				if (po != null) {
					temp = new DepartmentPo();
					temp.setId(po.getId());
					temp.setName(depart.getName());
					temp.setParentId((long) depart.getParentId());
					temp.setSortOrder(depart.getOrder());
					temp.setSyncStauts(2);
					temp.setSyncTime(now);
					temp.setSyncType(1);
					temp.setStatus(1);
					departmentMapper.updateById(temp);
				} else {
					po = new DepartmentPo();
					po.setName(depart.getName());
					po.setParentId((long) depart.getParentId());
					po.setId((long) depart.getId());
					po.setSortOrder(depart.getOrder());
					po.setCreateTime(now);
					po.setModifyTime(now);
					po.setStatus(1);
					po.setSyncStauts(2);
					po.setSyncTime(now);
					po.setSyncType(1);
					po.setAddType(1);
					pos.add(po);
				}
			}
			if (CollectionUtils.isNotEmpty(pos)) {
				this.departmentMapper.insertByBatch(pos);
			}

		} catch (Exception e) {
			logger.warn("syncByDepart Exception: ", e);
		}
	}

	public void updateUser(String userid) throws Exception {
		/*WxCpUser cpUser = wxCpService.userGet(userid);
		if (cpUser != null) {
			UserInfoPo user = null;
			UserInfoPo temp = null;
			List<UserDepartmentPo> departs = new ArrayList<UserDepartmentPo>();
			user = this.userInfoMapper.queryByUserId(cpUser.getUserId());
			if (user != null) {
				temp = new UserInfoPo();
				temp.setId(user.getId());
				temp.setNickname(cpUser.getName());
				temp.setUserName(cpUser.getUserId().toLowerCase());
				temp.setName(cpUser.getName());
				temp.setMobile(cpUser.getMobile());
				temp.setPost(cpUser.getPosition());
				temp.setGender(cpUser.getGender());
				temp.setEmail(cpUser.getEmail());
				//cjianquan 2019/9/23 该字段以内部设置为准
//				temp.setIsLeader(cpUser.getIsleader());
				temp.setTelephone(cpUser.getTel());
				temp.setEnable(cpUser.getEnable());
				if (cpUser.getEnable() == null) {
					temp.setEnable(1);
				}
				temp.setEnglishName(cpUser.getEnglishName());
				temp.setCpStatus(cpUser.getStatus());
				temp.setQrCode(cpUser.getQrCode());
				temp.setPortrait(cpUser.getAvatar());
				String ids = CommonUtils.listToString(cpUser.getDepartIds(), ",");
				Date now = new Date();
				if (StringUtils.isNoneBlank(ids)) {
					userDepartmentMapper.deleteByUser(user.getId());
					temp.setDepartmentIds(ids);
					temp.setDepartment(this.departmentService.queryNameByIds(ids));
					UserDepartmentPo depart = null;
					for (int i = 0; i < cpUser.getDepartIds().length; i++) {
						depart = new UserDepartmentPo();
						depart.setUserId(user.getId());
						depart.setDepartmentId(cpUser.getDepartIds()[i].longValue());
						depart.setId(IdUtils.id());
						depart.setCreateTime(now);
						departs.add(depart);
					}
				}
				temp.setModifyTime(now);
				temp.setSyncStauts(2);
				temp.setSyncTime(now);
				temp.setSyncType(2);
				userInfoMapper.updateById(temp);
			} else {
				user = new UserInfoPo();
				Date now = new Date();
				user.setId(IdUtils.id());
				user.setCreateTime(now);
				user.setModifyTime(now);

				user.setName(cpUser.getName());
				user.setNickname(cpUser.getName());
				user.setUserName(cpUser.getUserId().toLowerCase());
				user.setUserId(cpUser.getUserId());
				String ids = CommonUtils.listToString(cpUser.getDepartIds(), ",");
				if (StringUtils.isNoneBlank(ids)) {
					user.setDepartmentIds(ids);
					user.setDepartment(this.departmentService.queryNameByIds(ids));
					UserDepartmentPo depart = null;
					for (int i = 0; i < cpUser.getDepartIds().length; i++) {
						depart = new UserDepartmentPo();
						depart.setUserId(user.getId());
						depart.setDepartmentId(cpUser.getDepartIds()[i].longValue());
						depart.setId(IdUtils.id());
						depart.setCreateTime(now);
						departs.add(depart);
						if (i == 0) {
							DepartmentPo department = this.departmentService
									.queryById(cpUser.getDepartIds()[i].longValue());
							if (department != null && department.getServiceType() != null
									&& department.getServiceType() == 1) {
								user.setRole("销售顾问");
								user.setRoleIds("1610838954737752");
								user.setPosition("销售顾问");
								user.setPositionId(1610928587014419l);
							}
						}
					}
				}

				user.setMobile(cpUser.getMobile());
				user.setPost(cpUser.getPosition());
				user.setGender(cpUser.getGender());
				user.setEmail(cpUser.getEmail());
				user.setIsLeader(cpUser.getIsleader());
				user.setTelephone(cpUser.getTel());
				user.setEnable(cpUser.getEnable());
				if (cpUser.getEnable() == null) {
					user.setEnable(1);
				}
				user.setEnglishName(cpUser.getEnglishName());
				user.setCpStatus(cpUser.getStatus());
				user.setQrCode(cpUser.getQrCode());
				user.setPortrait(cpUser.getAvatar());

				user.setStatus(1);
				user.setIsLock(false);
				user.setAddType(1);
				user.setSyncStauts(2);
				user.setSyncTime(now);
				user.setSyncType(2);
				user.setPassword(CommonUtils.md5(CommonUtils.INIT_PASSWORD));
				userInfoMapper.insert(user);
			}
			if (CollectionUtils.isNotEmpty(departs)) {
				this.userDepartmentMapper.insertByBatch(departs);
			}
		}*/
	}

	public void updateDepartment(String id) throws Exception {
		List<WxCpDepart> departs = wxCpService.departGet(id);
		List<DepartmentPo> pos = new ArrayList<DepartmentPo>();
		DepartmentPo po = null;
		DepartmentPo temp = null;
		for (WxCpDepart depart : departs) {
			po = this.departmentMapper.queryById((long) depart.getId());
			Date now = new Date();
			if (po != null) {
				temp = new DepartmentPo();
				temp.setId(po.getId());
				temp.setName(depart.getName());
				temp.setParentId((long) depart.getParentId());
				temp.setSortOrder(depart.getOrder());
				temp.setSyncStauts(2);
				temp.setSyncTime(now);
				temp.setSyncType(1);
				departmentMapper.updateById(temp);
			} else {
				po = new DepartmentPo();
				po.setName(depart.getName());
				po.setParentId((long) depart.getParentId());
				po.setId((long) depart.getId());
				po.setSortOrder(depart.getOrder());
				po.setCreateTime(now);
				po.setModifyTime(now);
				po.setStatus(1);
				po.setSyncStauts(2);
				po.setSyncTime(now);
				po.setSyncType(1);
				po.setAddType(1);
				pos.add(po);
			}
		}
		if (CollectionUtils.isNotEmpty(pos)) {
			this.departmentMapper.insertByBatch(pos);
		}
	}
}